(function() {
  Registry.require("kankan");
  document.addEventListener('DOMContentLoaded', () => {
    const url = new URL(window.location.href);
    console.log('URL:', url);
    const queryParam = url.searchParams.get('q');
    console.log(`Loading search module: ${queryParam}`);

    const searchBox = document.getElementById('searchBox');
    if(queryParam) {
      searchBox.value = queryParam;
    }
    const searchButton = document.getElementById('searchButton');
    searchButton.addEventListener('click', () => {
      console.log('search button clicked');
      const query = searchBox.value;
      console.log(`Loading search module: ${query}`);
      if(query) {
        Kankan.searchVideo(query);
        // fetchSearchList(query);
      }
    });
    console.log('init search page finished');
  });

  async function fetchRecommended() {
  }

  function renderRecommended(recommendedItems) {
  }

  async function fetchSearchList(query) {
    console.log(`fetchSearchList ${query}`)
    document.getElementById('searchContainer').classList.add('searching');

    document.getElementById('status').innerText = 'Searching...';
    document.getElementById('results').innerHTML = '';

    doFetchSearchResults(query, renderSearchList);
  }

  function renderSearchList(newResults, siteInFetching) {
    if(siteInFetching === 0) {
      document.getElementById('status').innerText = '';
    } else {
      document.getElementById('status').innerText = `(${siteInFetching} sites in searching...)`;
    }

    if(newResults == null) return;
    let content = '';
    newResults.forEach(item => {
      content += `
      <a class="result-item" href="${item.link}">
        <div class="result-image-wrapper">
          <img src="${item.image}" alt="${item.title}" class="result-image" onerror="this.style.display='none';">
          <div class="site-info">
            <img src="${item.site_icon}" alt="${item.site_name}" class="site-icon">
            <span class="site-name">${item.site_name}</span>
          </div>
        </div>
        <div class="result-info">
          <p class="result-title">${item.title}</p>
          <p class="result-description">${item.description}</p>
        </div>
      </a>
    `;
    });
    document.getElementById('results').innerHTML += content;
  }

  function onPluginsLoaded() {
    const searchBox = document.getElementById('searchBox');
    if(searchBox.value) {
      const searchButton = document.getElementById('searchButton');
      searchButton.click();
    } else {
      fetchRecommended();
    }
  }
})();
